﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TicketReservationSystemDataLayer
{
    public class PurchaseDAO
    {
        //returns the ID of the purchase
        public static int CreatePurchase(
            TicketReservationSystemDataContext context, int eventId,
            string name, int count, string address)
        {
            Purchase purchase = new Purchase();
            purchase.CustomerName = name;
            purchase.EventId = eventId;
            purchase.ShippingAddress = address;
            purchase.NumberOfTickets = count;
            purchase.DateOdPurchase = DateTime.Now;
            context.Purchases.InsertOnSubmit(purchase);
            context.SubmitChanges();
            return purchase.Id;
        }

        public static IQueryable<Purchase> GetDeliveredPurchases(
            TicketReservationSystemDataContext context)
        {
            var purchases =
                from p in context.Purchases
                where p.IsDelivered
                orderby p.DateOdPurchase
                select p;
            return purchases;
        }

        public static IQueryable<Purchase> GetNotDeliveredPurchases(
           TicketReservationSystemDataContext context)
        {
            var purchases =
                from p in context.Purchases
                where !p.IsDelivered
                orderby p.DateOdPurchase
                select p;
            return purchases;
        }

        public static IQueryable<Purchase> GetPurchaseByNumber(
            TicketReservationSystemDataContext context, string number)
        {
            try
            {
                int purchaseId = int.Parse(number);
                var purchase =
                    from p in context.Purchases
                    where p.Id == purchaseId
                    select p;
                if (purchase.Count() == 0)
                {
                    return null;
                }
                return purchase;
            }
            catch
            {
                return null;
            }
        }

        public static void ChangePurchaseStatus(
            TicketReservationSystemDataContext context, int purchaseId)
        {
            Purchase purchase = GetPurchaseByNumber(context, purchaseId.ToString()).First();
            purchase.IsDelivered = true;
            context.SubmitChanges();
        }
    }
}
